package com.hanxiaozhang.itextpdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Base64Utils;

import java.util.List;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 * <p>
 * https://blog.csdn.net/fangdengfu123/article/details/118081552
 *
 * @author hanxinghua
 * @create 2024/12/6
 * @since 1.0.0
 */
@Slf4j
public class ItextPdfDemo {

    public static void main(String[] args) throws Exception {

        // 创建一个新的PDF文档对象
        Document document = new Document(PageSize.A4);

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\han\\Desktop\\PDF\\output.pdf"));
        document.open();

        // 设置样式
        Font font = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.RED);
        Paragraph paragraph = new Paragraph("Hello, World!", font);


        // 添加内容
        document.add(paragraph);
        document.close();
        writer.close();


    }


    /**
     * 新建一个pdf，并追加图片
     *
     * @param dest        输出文件
     * @param signDetails 图片详细
     */
    public static void newPdf(String dest, List<String> signDetails) {
        File file = new File(dest);
        if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(dest);
            Document document = new Document(PageSize.A4);

            PdfWriter writer = PdfWriter.getInstance(document, fos);
            document.open();

            // 加载模板文件
            ClassPathResource resource = new ClassPathResource("tpl/signTpl.pdf");
            PdfReader reader = new PdfReader(resource.getInputStream());
            PdfImportedPage page = writer.getImportedPage(reader, 1);
            PdfContentByte cb = writer.getDirectContent();

            document.newPage();
            cb.addTemplate(page, 0, 0);

            float top = document.top();
            // 默认顶部拿掉，然后再扣掉页眉的高度
            float y = top - 66 - 20;
            float x = 36;
            int signHeight = 75;
            int rowCount = 3;
            for (int i = 0; i < signDetails.size(); i++) {
                String detail = signDetails.get(i);
                x = 90 + (i % rowCount) * 150;

                Image image = buildImageFromSource(detail, 214, 148);
                if (i % rowCount == 0) {
                    y -= signHeight;
                    if (y <= signHeight) {
                        document.newPage();
                        cb.addTemplate(page, 0, 0);
                        y = top - 66 - 90;
                    }
                }
                if (image != null) {
                    image.setAbsolutePosition(x, y);
                    document.add(image);
                }
            }

            document.close();

        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    /**
     * signDetail 前端canvas 获取的图片信息
     */
    private static Image buildImageFromSource(String signDetail, float width, float height) {
        try {
            signDetail = clearPreffix(signDetail);
            Image image = Image.getInstance(Base64Utils.decodeFromString(signDetail));

            image.setAlignment(Image.LEFT);
            image.setBorder(Image.NO_BORDER);
            // 将px转成pt  需要 * 0.75，计算完成后，减去上下左右的36pt的边距
            image.scaleAbsolute((width * 0.75f) - 72, (height * 0.75f) - 72);

            return image;
        } catch (BadElementException | IOException e) {
            e.printStackTrace();
            log.error("创建image失败: {}", e.getMessage());
        }
        return null;
    }

    /**
     * 移除保存图片时不需要的前缀
     *
     * @param detail
     * @return
     */
    private static String clearPreffix(String detail) {
        if (detail.startsWith("data")) {
            // 获取点的位置
            int pointIdx = detail.indexOf(",");
            detail = detail.substring(pointIdx + 1);
        }
        return detail;

    }


//    public static void appendImgToPdf(String sourcePath, String targetPath, List<String> details) throws IOException {
//        String tempPath = new File("/tmp/test").getAbsolutePath() + "/" + UUID.randomUUID().toString() + ".png";
//        newPdf(tempPath, details);
//        mergePdf(Lists.newArrayList(sourcePath, tempPath), targetPath);
//    }
//
//    public static void mergePdf(List<String> sourceFilePaths, String targtPath) throws IOException {
//        PDFMergerUtility mergePdf = new PDFMergerUtility();
//        for (String filePath : sourceFilePaths) {
//            File file = new File(filePath);
//            if (file.exists() && file.isFile()) {
//                mergePdf.addSource(file);
//            }
//        }
//        File file = new File(targtPath);
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdirs();
//        }
//        mergePdf.setDestinationFileName(targtPath);
//        mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
//    }


}
